const redirectLogin = () => {
  // setAuthorizationToken('')
  // window.vue.$router.replace('/login')
  logout()
}

const login = (username, password, successCallBack) => {
  window.vue.axios.post('/login', {username: username, password: password}).then((response) => {
    window.sessionStorage.setItem('currentUser', JSON.stringify(response.data))
  }).then(() => {
    window.vue.axios.get('/system/menus/actions').then((response) => {
      window.sessionStorage.setItem('menuActions', JSON.stringify(response.data))
      if (successCallBack) {
        successCallBack()
      }
    })
  }).catch(error => {
    // ignore
    console.log(`error: ${error}`)
  })
}

const hasLogin = () => {
  return window.sessionStorage.getItem('currentUser') !== null
}

const hasPermission = (permission) => {
  if (!permission || permission === '') {
    return true
  }
  return true
  // let permissionArray = permission.split(':')
  // if (permissionArray.length !== 2) {
  //   console.log(`invalid permission expression: ${permission}`)
  //   return false
  // }

  // let menu = permissionArray[0]
  // let menuActions = getMenuActions()
  // let authActions = menuActions[menu]
  // if (!authActions || authActions === '') {
  //   return false
  // }
  // if (authActions === '*') {
  //   return true
  // }
  // return authActions.indexOf(permissionArray[1]) !== -1
}

const logout = () => {
  // TODO nitify server
  window.vue.axios.get('/logout').then((response) => {
    window.vue.$router.replace('/login')
  })
  window.sessionStorage.clear()
}

// private
// const fetchMenuActions = () => {
//   window.vue.axios.get('/system/menus/actions').then((response) => {
//     window.sessionStorage.setItem('menuActions', JSON.stringify(response.data))
//   })
// }

// const getMenuActions = () => {
//   let menuActions = window.sessionStorage.getItem('menuActions')
//   if (!menuActions) {
//     return {}
//   }
//   return JSON.parse(menuActions)
// }

export {
  redirectLogin,
  login,
  logout,
  hasLogin,
  hasPermission
}
